package org.pine.dictionary.common;


import org.pine.dictionary.bean.LogId;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>
 * 日志ID拦截器
 * </p>
 *
 * @author pine
 * @since 2024-05-17
 */
public class LogIdHandlerInterceptor implements HandlerInterceptor {

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Headers", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
        // 加上校验放行
        if ("OPTIONS".equals(request.getMethod())) {
            return true;
        }

        setLogId(request);
        return true;
    }

    private void setLogId(HttpServletRequest request) {
        // 从请求头中获取logId
        String logId = request.getHeader(LogId.KEY_MDC);
        if (StringUtils.hasLength(logId)) {
            LogId.put(logId);
            return;
        }
        LogId.get();
    }
}
